package com.boot.configstatistical.repair;

import com.alibaba.fastjson.JSONObject;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author songlin.an
 * @className Test
 * @description 重百赊销重复支付修复脚本
 * @date 2023/5/18 11:07
 **/
public class CBSXRepeatedPayRepairScript {

    public static void main(String[] args) throws Exception {
        List<Long> longs = Arrays.asList(
                725866795440L,
                725767911332L,
                722585043368L,
                722503762132L,
                722514194645L,
                723559939776L,
                723554015090L,
                723477731219L,
                723504070368L,
                723499175814L,
                723524678210L,
                723732010720L,
                723680498649L,
                723717123415L,
                724645858861L,
                725575771211L,
                725854774599L,
                725785543025L,
                722353562598L,
                722841279972L,
                723585219754L,
                721443050984L,
                723260076046L,
                723708306151L,
                725468319127L
        );
        for (Long aLong : longs) {
            deal(aLong);
        }
    }


    public static void deal(Long orderId) throws Exception {
        String cookie = "GALAXY_OFFLINE_CLIENT_WEB_VERSION_9e74bd830361046daa00798aa282f1fe=10; dhrUserId=9157561; login_user_name=%E5%AE%89%E6%9D%BE%E6%9E%97; login_type=vpn; loginType=account; updateTime=1698975029000; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2218ba7d63fe0633-02cc4ef12e489f-26031051-2304000-18ba7d63fe1cdc%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMThiYTdkNjNmZTA2MzMtMDJjYzRlZjEyZTQ4OWYtMjYwMzEwNTEtMjMwNDAwMC0xOGJhN2Q2M2ZlMWNkYyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218ba7d63fe0633-02cc4ef12e489f-26031051-2304000-18ba7d63fe1cdc%22%7D; inited=true; login_dmall_id=songlin.an; return_url=https://one.dmall.com/#index/dmalloneweb/home; login_token=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDE2NTQ1MTY2NTgsImV4cCI6MTcwMjI1OTMxNjY1OCwiaXNzIjoia2VuIiwiZGF0YSI6eyJ1c2VyX2luZm8iOnsidXNlcl9pZCI6OTE1NzU2MSwidXNlcl9jb2RlIjoic29uZ2xpbi5hbiIsInVzZXJfbmFtZSI6Ilx1NWI4OVx1Njc3ZVx1Njc5NyIsInByZWZlcnJlZF9uYW1lIjoiXHU1Yjg5XHU2NzdlXHU2Nzk3IiwicGhvbmUiOiIiLCJlbWFpbCI6InNvbmdsaW4uYW5AZG1hbGwuY29tIiwiaHJzX2lkIjo4NjQzOTYxLCJocm1zX2lkIjoxMDAwMTMwODQxLCJ1c2VyX25vIjoiMTAwMDAxMjU4In0sImxvZ2luX3RpbWUiOjE3MDE2NTQ1MTY2NTh9fQ.2l7PGPleYDw5t4pF9yBJLeNfVcPN72QMHNIHQn-Idf0; UYBFEWAEE=EA970CF573B5F3A0725F0C06D37B02DBC3DD18CF3A4AD3A8B5D9EDA5542436333E0994E5D822F51EF3EA220922DFC1C996969E3CEABDE8010C28C8E10DB6EC99A981510C3196C82723F90D29F9E2ED8C; login_no=\"RGQxMDAwMDEyNThfMTU1MzM3ODM5NTc=\"; envRootDomain=dmall.com; appname=cloud; username=songlin.an; timeZone=Asia/Shanghai; language=zh; signature=2bab62f2067e27be44c264a6a3284521; timestamp=1701914465; wm_menu_id=menu_4835";
        cookie = "GALAXY_OFFLINE_CLIENT_WEB_VERSION_9e74bd830361046daa00798aa282f1fe=10; dhrUserId=9157561; loginType=account; login_token=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MTA3Mjg2MjI4NDEsImV4cCI6MTcxMTMzMzQyMjg0MSwiaXNzIjoia2VuIiwiZGF0YSI6eyJ1c2VyX2luZm8iOnsidXNlcl9pZCI6OTE1NzU2MSwidXNlcl9jb2RlIjoic29uZ2xpbi5hbiIsInVzZXJfbmFtZSI6Ilx1NWI4OVx1Njc3ZVx1Njc5NyIsInByZWZlcnJlZF9uYW1lIjoiXHU1Yjg5XHU2NzdlXHU2Nzk3IiwicGhvbmUiOiIiLCJlbWFpbCI6InNvbmdsaW4uYW5AZG1hbGwuY29tIiwiaHJzX2lkIjo4NjQzOTYxLCJocm1zX2lkIjoxMDAwMTMwODQxLCJ1c2VyX25vIjoiMTAwMDAxMjU4In0sImxvZ2luX3RpbWUiOjE3MTA3Mjg2MjI4NDF9fQ.tBl5ZMarhqPVXztLm1EHZt5yyczthkC7LpqtJ4tNFB4; login_user_name=%E5%AE%89%E6%9D%BE%E6%9E%97; login_type=vpn; login_dmall_id=songlin.an; UYBFEWAEE=3D4A524DAE907C906E573B7E5005FD5DA5590CC401640915A0B0C1CF5699710B3E0994E5D822F51EF3EA220922DFC1C9429E86778EA4D9317C42E2B17D90020FA981510C3196C82723F90D29F9E2ED8C; login_no=\"RGQxMDAwMDEyNThfMTU1MzM3ODM5NTc=\"; envRootDomain=dmall.com";
        String ledgerTradeNo = getLedgerTradeNo(String.valueOf(orderId), cookie);

           // 输出响应内容
            HashMap<String,Response.Row> map = new HashMap();

            //获取支付接口列表
            List<Response.Row> payInfo = getPayInfo(orderId,cookie);
            if(payInfo.size() >= 3){
                System.out.println("##################### 三单的数据 :" +orderId);
            }
            for (Response.Row row : payInfo) {
                String tradeNo = row.getTradeNo();
                if(row.getPayWayName().contains("赊销") && !tradeNo.equals(ledgerTradeNo) && row.getReverseStatusStr() == null ) {
                    map.put(tradeNo, row);
                }
            }

            Set<Map.Entry<String, Response.Row>> entrySet = map.entrySet();
            for (Map.Entry<String, Response.Row> entry : entrySet) {
                Response.Row value = entry.getValue(); // 获取值
                String externalTradeNo = value.getExternalTradeNo();
                HttpClientUtils.doGet("http://10.28.12.220:8080/backdoor/reverse?extTradeNos="+externalTradeNo);
                System.out.println("单号:"+orderId +"   处理成功。。。。"+externalTradeNo);
            }
    }

    public static String getLedgerTradeNo(String orderId,String cookie) throws Exception {
        String url = "http://man.ledger.dmall.com/ledger/paymentinfo/2/" + orderId + "?includePD=true";
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .sslSocketFactory(SSLOkHttpClient.getSSLSocketFactory(), SSLOkHttpClient.getX509TrustManager())
                .hostnameVerifier(SSLOkHttpClient.getHostnameVerifier())
                .build();

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", cookie)
                .url(url)
                .get()
                .build();

        Call call = client.newCall(request);
        okhttp3.Response response = call.execute();
        String result = Objects.requireNonNull(response.body()).string();
        String s = result.replaceAll(" ", "").replaceAll("\t\n", "").replaceAll("\r\n", "");
        String[] split = s.split("<tdclass=\"centercol-xs-4\">");

        try {
            if (split[1].contains("重百-赊销客户支付")) {
                System.out.print(orderId + "|");
                System.out.print(split[2].replace("</td>", "") + "|");
                System.out.println(split[3].replace("</td></tr></tbody></table></div></div></body></html>", ""));

                return split[2].replace("</td>", "").trim();
            } else {
                System.out.print(orderId + "|");
                System.out.println("数据需要校验");
            }
        } catch (Exception e) {
            System.out.print(orderId + "|");
            System.out.println("数据需要校验1");

        }

        return null;

    }


    private static List<Response.Row> getPayInfo(long orderNo,String cookie) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        String url = "http://man.paycenter.pay.dmall.com/payTrade/list/pageQuery";
        HttpPost httpPost = new HttpPost(url);

        // 设置Cookie
        httpPost.addHeader("Cookie",cookie);
        // 设置请求参数
        HttpEntity entity = MultipartEntityBuilder.create()
                .addPart("orderNo", new StringBody(String.valueOf(orderNo), ContentType.TEXT_PLAIN))
                .addPart("limit", new StringBody("10", ContentType.TEXT_PLAIN))
                .addPart("order", new StringBody("asc", ContentType.TEXT_PLAIN))
                .addPart("limit", new StringBody("10", ContentType.TEXT_PLAIN))
                .addPart("isHistory", new StringBody("false", ContentType.TEXT_PLAIN))
                .addPart("offset", new StringBody("0", ContentType.TEXT_PLAIN))
                .build();
        httpPost.setEntity(entity);

        // 发送请求
        HttpResponse response = httpClient.execute(httpPost);

        // 处理响应
        String result = EntityUtils.toString(response.getEntity());
        Response response1 = JSONObject.parseObject(result, Response.class);
        System.out.println(response1);
        return response1.getRows();
    }
}
